<!--
*@Author: zt
*@Description: 单位管理
*@Date: 2024-08-14
-->
<template>
  <a-layout class="f-h-100">
    
    <u-collapsed-sider
      class="f-padding-6">
      <u-tree :treeData="treeData" ref="treeRef" 
        v-model:expandedKeys="treeExpandes" 
        :showSearch="false"
        :fieldNames="{ title: 'name', key: 'keyid', children: 'children' }"
        @select="treeClick" />
    </u-collapsed-sider>
    <a-layout-content class="s-bg-white" style="margin-left: 12px; padding: 12px">
      <a-layout class="f-h-100">
        <a-layout-header class="f-h-auto " 
          style="padding: 0 0 12px; line-height: unset; background: #fff">
          <a-space>
            <u-icon-button itype="add" @click="addBtn">新增子级</u-icon-button>
            <u-icon-button itype="save" @click="submit"
              :disabled="form['keyid'] == -1"> 保存
            </u-icon-button>
            <u-icon-button itype="delete" @click="deleteBtn"
              :disabled="form['keyid'] == -1"> 删除
            </u-icon-button>
          </a-space>
        </a-layout-header>
        <a-layout-content class="s-bg-white"  style="padding: 0;">
          <u-loading-box :spinning="loading">
            <u-form :elements="elements" :model="form" ref="formRef" v-bind="$attrs" />
          </u-loading-box>
        </a-layout-content>
      </a-layout>
    </a-layout-content>
  </a-layout>
</template>
<script lang="ts" setup>
import { isSel } from '@/common/model/base';
import  * as unitService from '@/service/system/unit/index';
import { disableTreeKeyid } from '@/util/format.ts'
import { alertC } from '@/util/common'

import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { confirmC, isValue, nullC } from '@/util/common';
// import { createNamespacedHelpers } from 'vuex';
// const { mapGetters } = createNamespacedHelpers("loginStore")

const  baseForm =ref({})
let  treeCurrentData =reactive<any>({})
const  treeData =ref([])
const  treeExpandes =ref([])

const  loading = ref(false)

const  form = reactive<any>( {
        isuse: '1',
        fkparentid: '',
        name: '',
        code: '',
        remark: '',
        keyid: '',
      })

 const  elements =reactive([
        { element: 'treeselect', label: '父级', col: { span: 24 }, key: 'fkparentid', 
          formItemProps: { labelWidth: '90px' },
          componentProps: {  
            required: true, 
            treeData: computed(()=>treeData.value),
            fieldNames: { label: "name", value: "keyid" },
          }
        },
        { element: 'input', label: '单位名称', col: { span: 24 }, key: 'name', 
          formItemProps: { labelWidth: '90px' },
          componentProps: {  required: true, options: [], maxlength: 50, showCount: true }
        },
        { element: 'number', label: '单位代码', col: { span: 24 }, key: 'code', 
          formItemProps: { labelWidth: '90px' },
          componentProps: {  required: true, options: [], precision: 0}
        },
        { element: 'textarea', label: '备注', col: { span: 24 }, key: 'remark',
          formItemProps: { labelWidth: '90px' },
          componentProps: { maxlength: 200, showCount: true, }
        },
        { element: 'select', label: '是否启用', col: { span: 24 }, key: 'isuse', data: [],
          formItemProps: { labelWidth: '90px' },
          componentProps: {  required: true, options: isSel() }
        },
      ] )

      onMounted(() => {
        getTree('init')
      })

      // computed(() => {
      //   ...mapGetters(['getUserInfo'])
      // })

       // 获取树形
    // type = init 为初次进入时的加载
  const  getTree=(type?:string)=> {
      return unitService.tree('').then(res => {
        if (res.code == 0) {
          treeData.value = res.data;
          elements.splice(0, 1, { ...elements[0], data: treeData.value });
          if (treeData.value.length != 0 && type == 'init') {
            treeExpandes.value.splice(0, treeExpandes.value.length, treeData[0]['keyid'])
          }
        }
      })
      .catch(() => { })
    }

const formRef =ref()
     // 左侧树形点击
   const  treeClick=(keys, { node })=> {
      formRef.value.form.resetFields()
      treeCurrentData = node.dataRef;
       form.keyid = treeCurrentData['keyid'];
      loading.value = true;
      clearValidate();
      unitService.singleQuery(treeCurrentData.keyid).then(res => {
        loading.value = false;
        if (res.code == 0) {
          for(let key in form) {
            if(isValue(res.data[key])) {
              form[key] = res.data[key];  
            }
          }
          form.fkparentid = treeCurrentData.fkparentid;
          form.isuse = nullC(form.isuse) + '';
          elements.splice(0, 1, { ...elements[0], data: disableTreeKeyid(treeData, keys['keyid'])})
          clearValidate();
          getTree()
        }
      })
      .catch(() => {
        loading.value = false;
      })
    }

    const treeRef = ref()
 // 保存
const submit=()=> {
      if(form['keyid'] == 1) {
        alertC("顶级节点不能修改!");
        return
      }

      if(!treeCurrentData['keyid']) {
        alertC("请先在左侧选择节点!");
        return
      }

      formRef.value.form.validate().then((vali) => {
        if (!vali) {
          alertC("请先将必填字段填写完毕!");
          return
        }

        const url =form.keyid ? 'update' : 'add';
        const msg = form.keyid ? '确认修改?' : '确认新增?';

        // 提交保存
        loading.value= true;
        unitService[url](form).then(async res => {
          loading.value = false;
          if (res.code == 0) {
            alertC(res.msg, "success");
            
            clearValidate();
            getTree()
            if(res.data) {
              for(let key in form) {
                if(isValue(res.data[key])) {
                  form[key].value = res.data[key];
                }
              }
              treeCurrentData = res.data;
            }
            form.isuse =nullC(form.isuse) + '';
            
            await getTree(form.fkparentid == '0' ? 'init' : '');
            nextTick(() => {
              treeRef.value.tree.setCurrentKey(form.keyid)
            })
            if(form.fkparentid != 0) {
              treeExpandes.value.splice(0, treeExpandes.value.length, form.fkparentid)
            }
           
          }
          else {
            alertC(res.msg, 'warning');
          }
        })
        .catch(error => {
          loading.value = false;
        })
      })
    }


    // 删除
   const deleteBtn =()=> {
      if (!isValue(treeCurrentData['keyid'])) {
        alertC("请选择要删除的节点!");
        return
      }

      if (treeCurrentData['fkparentid'] == 0) {
        alertC("不能删除顶级节点!");
        return
      }

      clearValidate();
        unitService.del({ ids: treeCurrentData['keyid'] }).then(res => {
          if (res.code == 0) {
            alertC(res.msg, "success");
            getTree()
           formRef.value.form.resetFields();
            form.keyid = "";
            treeCurrentData = {};
            form.fkparentid = '';
          }
          else {
            alertC(res.msg, 'warning');
          }
        })
        .catch(err => { })

      // 确认删除
      // confirmC({msg: '确认删除?'}).then(() => {
        
       

      // })
      // .catch(err => {})
    }
// 新增子级
const addBtn =()=>{
      if (!isValue(treeCurrentData['keyid'])) {
        alertC("请先在左侧选择节点!");
        return
      }
      
      formRef.value.form.resetFields();
      form['fkparentid'] = treeCurrentData['keyid']
      form['keyid'] = ''
      form['isuse'] = '1'

      let index = elements.findIndex(item => item.key == 'fkparentid');
      elements.splice(index, 1, { ...elements[index], disabled: true })
      clearValidate();
    }

     // 清除已有的表单验证结果
    const clearValidate = ()=> {
      nextTick(() => {
        formRef.value.form.clearValidate();
      })
    }
    watch(() => form.keyid,(nval)=>{
      if(isValue(nval)) {
        let index = elements.findIndex(item => item.key == 'fkparentid');
        if(index != -1) {
          elements.splice(index, 1, { ...elements[index], disabled: nval && nval != '-1' ? false : true })
        }
      }
})
</script>
<style lang='scss'></style>